package com.wave.gate.netty;

import com.alibaba.fastjson2.JSON;
import com.wave.gate.dto.FaceOperation;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FaceEncoder extends MessageToByteEncoder<FaceOperation> {

    public static byte m_num = 0;
    @Override
    protected void encode(ChannelHandlerContext ctx, FaceOperation faceOperation, ByteBuf out) throws Exception {
        log.info("faceEncoder,给人脸机发送消息ip:{},msg:{},doType:{}", ctx.channel().remoteAddress(), faceOperation.getMessage(),faceOperation.getDoType());
        String content = JSON.toJSONString(faceOperation);
        byte[] data = getData(content.getBytes());
        out.writeBytes(data);
    }

    public static byte[] getData(byte[] data) {
        int dataLength = data.length;
        //log.info("发送数据内容长度为:{}", dataLength);
        byte[] bytesData = new byte[data.length + 6];
        bytesData[0] = (byte) 0xFA;
        bytesData[1] = m_num;
        bytesData[2] = 0x00;
        bytesData[3] = (byte) ((dataLength >> 2) & 0xFF);
        bytesData[4] = (byte) (dataLength & 0xFF);
        System.arraycopy(data, 0, bytesData, 5, data.length);
        bytesData[bytesData.length - 1] = checkSum(bytesData, bytesData.length - 1);
        //log.info("发送数据校验位为:{}", bytesData[bytesData.length - 1]);
        m_num++;
        return bytesData;
    }

    public static byte checkSum(byte[] inBytArr, int byteCount) {
        byte result = 0;
        for (int i = 0; i < byteCount; ++i) {
            result ^= inBytArr[i];
        }
        return result;
    }
}
